Welcome to Authentication in Node.js. After watching this video, you will be able to: Discuss advantages of token-based authentication
in Node.js and implement token-based authentication and authorization
in Node.js. So, authentication is the process of confirming
a user's identity by obtaining credentials and using those credentials to validate their
identity. Authentication is meant to identify users
and provide access rights and contents depending on their id. As discussed in another video, authentication
can be achieved using the following approaches: Session Based Authentication; Token Based Authentication; and Passwordless Authentication. Token based authentication is the most popular
approach to implementing Authentication in Node.js. And the following are some of the advantages of using
Token based authentication. Token based authentication is more scalable
as the token only needs to be stored on the client side. Also, since the server only needs to verify
the token along with the user information, it is easier to handle multiple users. Token based authentication offers flexibility
as they can be used across multiple servers, and they can offer authentication for diverse
websites and applications at once. And JWT used in Token Based Authentication can
be signed and encrypted, which means they cannot be tampered with and also cannot be
read without the Private Encryption Key. Now let's set up an Express.js API server that
provides access to employee information based on their usage rights. The application will have 2 APIs, each with
its own endpoints. We will first use a POST API for logging in
that returns a web token to sign in by sending the username and password in the request body. The call to this API endpoint should be made
from the web server that hosts the application’s front end. And a second GET API will be the resource
endpoint to get employee information that only authenticated users can access. Let’s consider what this code might look
like. This code creates a web server module by calling
the "express()" function and assigning it to the constant “myapp." The myapp.get function creates a GET API endpoint
for the Employees API, and any call to this endpoint currently returns an HTTP status
code of 401. 401 means Not Authorized, with the message
"Please login to access this resource.“ The server also listens on Port 5000 for any
HTTP calls to the server and logs the message "API Server is localhost:5000" to the console. To execute the API first, save the file
and name it API server dot js. Now run the command: node api server dot js. To verify that the secure endpoint cannot
be accessed unless the user is authorized, run this curl command on the screen. In the output, you
should see the message: “Please login to access this resource per your code.” In the next part of the code, we allow users
to sign in and send back a verified generated token as long as the username and password
are correct. Generally, usernames and passwords are stored
in the database. However, since setting up a database connection
is out of the scope of this code demo, we will hardcode “user” and “password”
as the username and password in this code example. To generate the verified JWT, use the “jsonwebtoken”
npm package. Install it using the command “npm install
option save jsonwebtoken.” At the start, you will need to require the
module "jsonwebtoken” from the "jsonwebtoken" package. This module is used to generate the JWT using
the JWT secret. A constant is then declared to store the JWT
secret. The myapp dot use method enables returning
a JSON response by the API methods. To display the code in this video, we are
hardcoding the username and password. Please note, however, that the JWT Secret
should always be generated using a password generator and stored in the config file as
an environment variable and not hard coded in the API, as shown here. The username and password from the request
body is then compared with the values fetched from the database. Once the username and password match, the
JWT is generated using the "jsonwebtoken.sign()" function by including the username and the
JWT secret as parameters and is returned as a JSON response from the "signin" API. If the username and password match fails,
then a HTTP status code of 401 is returned with the message "Invalid username and/or
password." Next, we define the GET API method with the
employees’ endpoint. The token fetched from the call to the "signin"
API is passed in the Authorization header. The GET API ("employees") is updated to read
the Authorization header from the incoming API request using the request dot header function. If no header is found within the request,
then a Status code of 401 is sent back by the GET API with the message "No Token." The Authorization header always starts with
the string "BEARER" at the start of the header, and therefore, this token is also known as
Bearer Token. The fetched JWT is verified using the function
"jsonwebtoken.verify()" by passing the fetched token and the JWT Secret. The value returned by this function is then
used to verify if the user property matches with the username fetched from the database
and if that match happens, then the user is authenticated and is provided access to the employee's API. The API then returns the 200 Success Status
code with the message "Access Successful to Employee Endpoint.“ If the verification fails, then the 401 unauthorized
status code is sent back to the client with the message "Please login to access this resource.“
Lastly, write a listener function that listens for the response on port 5000, then log the
phrase “API server is local host 5000” to the console log. Recall that the code you just wrote has a
“signin” API endpoint that reads the username and password from the request body and then
validates it against the username and password stored in the database. If there is a match, it then uses the jsonwebtoken.sign()
method to generate the token and send it back in the response. In this video, you learned that: The advantages of token based authentication
include scalability, flexibility, and security. The POST API is used during authentication
to log a user in to an application. The GET API is used in authorization to determine
which resources a user can access. A JSON web token is used to authenticate a
user and authorize which resources they have access to use.